import 'package:sqflite/sqflite.dart';
import '../database/database_helper.dart';
import '../models/banner.dart';

class BannerService {
  final dbHelper = DatabaseHelper.instance;

  Future<int> insertBanner(BannerItem banner) async {
    Database db = await dbHelper.database;
    return await db.insert('banners', banner.toMap());
  }

  Future<List<BannerItem>> getAllBanners() async {
    try {
      Database db = await dbHelper.database;

      // 判断banners表是否存在
      var tables = await db.rawQuery(
          "SELECT name FROM sqlite_master WHERE type='table' AND name='banners'"
      );

      if (tables.isEmpty) {
        print('banners表不存在，需要先创建表');
        return [];
      }

      List<Map<String, dynamic>> maps = await db.query('banners');
      print('Banner data from DB: $maps');

      if (maps.isEmpty) {
        print('Banner表为空，添加默认数据');
        await addDefaultBanners();
        maps = await db.query('banners');
      }

      return List.generate(maps.length, (i) {
        try {
          return BannerItem.fromMap(maps[i]);
        } catch (e) {
          print('解析轮播图数据错误: $e');
          print('问题数据: ${maps[i]}');
          // 返回一个默认值防止崩溃
          return BannerItem(
            id: -1,
            imageUrl: 'https://via.placeholder.com/400x200?text=Error',
            description: '数据错误',
            websiteUrl: '',
            publisherId: 1,
          );
        }
      });
    } catch (e) {
      print('加载轮播图错误: $e');
      return [];
    }
  }

  Future<void> addDefaultBanners() async {
    print('添加默认轮播图');
    try {
      Database db = await dbHelper.database;

      // 查询管理员用户
      List<Map<String, dynamic>> adminUsers = await db.query(
        'users',
        where: 'isAdmin = ?',
        whereArgs: [1],
        limit: 1,
      );

      int publisherId = 1;
      if (adminUsers.isNotEmpty) {
        publisherId = adminUsers.first['id'];
      }

      // 添加默认轮播图
      await insertBanner(BannerItem(
        imageUrl: 'https://img.freepik.com/free-photo/rural-farm-landscape-with-green-fields_23-2149742424.jpg',
        description: '乡村振兴 - 绿色农业',
        websiteUrl: 'https://www.example.com/agriculture',
        publisherId: publisherId,
      ));

      await insertBanner(BannerItem(
        imageUrl: 'https://img.freepik.com/free-photo/beautiful-countryside-landscape-with-mountains_23-2149681977.jpg',
        description: '乡村旅游 - 美丽风光',
        websiteUrl: 'https://www.example.com/tourism',
        publisherId: publisherId,
      ));

      await insertBanner(BannerItem(
        imageUrl: 'https://img.freepik.com/free-photo/farmer-holding-fresh-vegetables-basket_23-2149681982.jpg',
        description: '农产品直销 - 新鲜健康',
        websiteUrl: 'https://www.example.com/products',
        publisherId: publisherId,
      ));

      print('默认轮播图添加完成');
    } catch (e) {
      print('添加默认轮播图错误: $e');
    }
  }

  Future<int> deleteBanner(int id) async {
    Database db = await dbHelper.database;
    return await db.delete(
      'banners',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  Future<BannerItem?> getBannerById(int id) async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'banners',
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return BannerItem.fromMap(maps.first);
    }
    return null;
  }
}